package com.yuniarti.konsultasikesehatan;

import static com.yuniarti.konsultasikesehatan.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.yuniarti.konsultasikesehatan.CommonUtilities.EXTRA_MESSAGE;
import static com.yuniarti.konsultasikesehatan.CommonUtilities.SENDER_ID;
import static com.yuniarti.konsultasikesehatan.CommonUtilities.SERVER_URL;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gcm.GCMRegistrar;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

public class AktifasiActivity extends Activity {

	/* gcm */
	AsyncTask<Void, Void, Void> mRegisterTask;
	// Connection detector
	ConnectionDetector cd;

	// alert dialog manager
	AlertDialogManager alert = new AlertDialogManager();
	/* endgcm */

	EditText un, pw, nl, tl;
	RadioGroup jk, gd;
	Button aktif;

	DataParser jsonParser = new DataParser();
	private static String cek_member = "http://konsultasi-yakes.web.id/JSON/aktifasi.php";
	// private static String cek_member =
	// "http://10.0.2.2/adminweb/JSON/aktifasi.php";
	private static final String TAG_HASIL = "hasil";

	public static String name;
	public static String email;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_aktifasi);

		un = (EditText) findViewById(R.id.idMember);
		nl = (EditText) findViewById(R.id.namalengkap);
		tl = (EditText) findViewById(R.id.tanggallahir);
		jk = (RadioGroup) findViewById(R.id.jekel);
		gd = (RadioGroup) findViewById(R.id.gol_darah);

		aktif = (Button) findViewById(R.id.btn_aktifasi);
		aktif.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {

				if ((un.length() == 0) && (nl.length() == 0)
						&& (tl.length() == 0)
						&& (jk.getCheckedRadioButtonId() == -1)
						&& (gd.getCheckedRadioButtonId() == -1)) {
					Toast.makeText(AktifasiActivity.this, "Data Masih Kosong",
							Toast.LENGTH_LONG).show();
				} else if (un.length() == 0) {
					Toast.makeText(AktifasiActivity.this,
							"Id Member Tidak Boleh Kosong", Toast.LENGTH_LONG)
							.show();
				} else if (nl.length() == 0) {
					Toast.makeText(AktifasiActivity.this,
							"Nama Lengkap Tidak Boleh Kosong",
							Toast.LENGTH_LONG).show();
				} else if (tl.length() == 0) {
					Toast.makeText(AktifasiActivity.this,
							"Tanggal Lahir Tidak Boleh Kosong",
							Toast.LENGTH_LONG).show();
				} else if (jk.getCheckedRadioButtonId() == -1) {
					Toast.makeText(AktifasiActivity.this,
							"Jenis Kelamin Tidak Boleh Kosong",
							Toast.LENGTH_LONG).show();
				} else if (gd.getCheckedRadioButtonId() == -1) {
					Toast.makeText(AktifasiActivity.this,
							"Golongan Darah Tidak Boleh Kosong",
							Toast.LENGTH_LONG).show();
				} else {

					String id_member = un.getText().toString();
					String namalengkap = nl.getText().toString();
					String tanggallahir = tl.getText().toString();

					String type = null;
					switch (jk.getCheckedRadioButtonId()) {
					case R.id.pria:
						type = "Pria";
						break;
					case R.id.wanita:
						type = "Wanita";
						break;
					default:
						break;
					}

					String gol = null;
					switch (gd.getCheckedRadioButtonId()) {
					case R.id.A:
						gol = "A";
						break;
					case R.id.B:
						gol = "B";
						break;
					case R.id.O:
						gol = "O";
						break;
					case R.id.AB:
						gol = "AB";
						break;
					default:
						break;
					}

					List<NameValuePair> params = new ArrayList<NameValuePair>();

					params.add(new BasicNameValuePair("id_member", id_member));
					params.add(new BasicNameValuePair("namalengkap",
							namalengkap));
					params.add(new BasicNameValuePair("tanggallahir",
							tanggallahir));
					params.add(new BasicNameValuePair("jekel", type));
					params.add(new BasicNameValuePair("gol", gol));

					JSONObject json = jsonParser.makeHttpRequest(cek_member,
							"POST", params);

					try {

						int hasil = json.getInt(TAG_HASIL);

						if (hasil == 1) {

							// createDialog("Aktifasi Berhasil",
							// "Gunakan id member sebagai password untuk login pertama kali");
							Toast.makeText(
									AktifasiActivity.this,
									"Aktifasi Berhasil YESSS!"
											+ "Gunakan id member sebagai password untuk login pertama kali",
									Toast.LENGTH_LONG).show();
							// Check if GCM configuration is set
							if (SERVER_URL == null || SENDER_ID == null
									|| SERVER_URL.length() == 0
									|| SENDER_ID.length() == 0) {
								// GCM sernder id / server url is missing
								alert.showAlertDialog(
										AktifasiActivity.this,
										"Configuration Error!",
										"Please set your Server URL and GCM Sender ID",
										false);
								// stop executing code by return
								return;
							}

							// String name = txtName.getText().toString();
							// String email = txtEmail.getText().toString();
							name = id_member;// =
													// un.getText().toString();
							email = namalengkap; // =
														// nl.getText().toString();

							// Check if user filled the form
							if (name.trim().length() > 0
									&& email.trim().length() > 0) {
								/*
								 * // Launch Main Activity Intent i = new
								 * Intent(getApplicationContext(),
								 * MainActivity.class);
								 * 
								 * // Registering user on our server // Sending
								 * registraiton details to MainActivity
								 * i.putExtra("name", name); i.putExtra("email",
								 * email); startActivity(i);
								 */
								prosesAktivasi(name, email);
								finish();
							} else {
								// user doen't filled that data
								// ask him to fill the form
								alert.showAlertDialog(AktifasiActivity.this,
										"Registration Error!",
										"Please enter your details", false);
							}

							finish();

						} else {

							Toast.makeText(
									AktifasiActivity.this,
									"Aktifasi Gagal, "
											+ "data yang anda masukan tidak sesuai dengan database kami!",
									Toast.LENGTH_SHORT).show();
						}

					} catch (JSONException e) {
						e.printStackTrace();
					}

				}
			}
		});
	}

	/*
	 * private void createDialog(String title, String text) { AlertDialog ad =
	 * new AlertDialog.Builder(this) .setPositiveButton("OK", null)
	 * .setTitle(title) .setMessage(text) .create(); ad.show(); }
	 */

	private void prosesAktivasi(final String name, final String email) {
		cd = new ConnectionDetector(getApplicationContext());

		// Check if Internet present
		if (!cd.isConnectingToInternet()) {
			// Internet Connection is not present
			alert.showAlertDialog(AktifasiActivity.this,
					"Internet Connection Error",
					"Please connect to working Internet connection", false);
			// stop executing code by return
			return;
		}

		// Getting name, email from intent
		// Intent i = getIntent();

		// name = i.getStringExtra("name");
		// email = i.getStringExtra("email");

		// Make sure the device has the proper dependencies.
		GCMRegistrar.checkDevice(this);

		// Make sure the manifest was properly set - comment out this line
		// while developing the app, then uncomment it when it's ready.
		GCMRegistrar.checkManifest(this);

		registerReceiver(mHandleMessageReceiver, new IntentFilter(
				DISPLAY_MESSAGE_ACTION));

		// Get GCM registration id
		final String regId = GCMRegistrar.getRegistrationId(this);

		// Log.d("cik name woi", name);
		// Log.d("cik email woi", email);
		// Log.d("cik regId woi", regId);

		// Check if regid already presents
		if (regId.equals("")) {
			// Registration is not present, register now with GCM
			GCMRegistrar.register(this, SENDER_ID);
		} else {
			// Device is already registered on GCM
			if (GCMRegistrar.isRegisteredOnServer(this)) {
				// Skips registration.
				Toast.makeText(getApplicationContext(),
						"Already registered with GCM", Toast.LENGTH_LONG)
						.show();
			} else {
				// Try to register again, but not in the UI thread.
				// It's also necessary to cancel the thread onDestroy(),
				// hence the use of AsyncTask instead of a raw thread.
				final Context context = this;
				mRegisterTask = new AsyncTask<Void, Void, Void>() {

					@Override
					protected Void doInBackground(Void... params) {
						// Register on our server
						// On server creates a new user
						ServerUtilities.register(context, name, email, regId);
						Log.d("cik name", name);
						Log.d("cik email", email);
						Log.d("cik regId", regId);
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						mRegisterTask = null;
					}

				};
				mRegisterTask.execute(null, null, null);
			}
		}
	}

	/**
	 * Receiving push messages
	 * */
	private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
			// Waking up mobile if it is sleeping
			WakeLocker.acquire(getApplicationContext());

			/**
			 * Take appropriate action on this message depending upon your app
			 * requirement For now i am just displaying it on the screen
			 * */

			// Showing received message
			// lblMessage.append(newMessage + "\n");
			// Toast.makeText(getApplicationContext(), "New Message: " +
			// newMessage, Toast.LENGTH_LONG).show();

			// Releasing wake lock
			WakeLocker.release();
		}
	};

	@Override
	protected void onDestroy() {
		if (mRegisterTask != null) {
			mRegisterTask.cancel(true);
		}
		try {
			unregisterReceiver(mHandleMessageReceiver);
			GCMRegistrar.onDestroy(this);
		} catch (Exception e) {
			Log.e("UnRegister Receiver Error", "> " + e.getMessage());
		}
		super.onDestroy();
	}

}
